﻿using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Security;
using WebInstagram.Models;

namespace WebInstagram.API
{
    public class AccountController : ApiController
    {
        ApplicationUserManager manager;
        public AccountController()
        {
            var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
            manager = new ApplicationUserManager(store);
        }
        [HttpPost]
        public IHttpActionResult Register(RegisterViewModel model)
        {

            if (ModelState.IsValid && model.Password == model.ConfirmPassword)
            {
                try
                {

                    var user = new ApplicationUser() { Email = model.Email, UserName = model.Name };
                    var result = manager.Create(user, model.Password);
                    model.Error = result.Errors.FirstOrDefault();
                }
                catch (Exception ex)
                {
                    model.Error = ex.Message;
                }

            }
            else
                model.Error = "Invalid credentials";

            if (string.IsNullOrWhiteSpace(model.Error))
                return Ok(model);
            else
                return InternalServerError(new Exception(model.Error));
        }


        [HttpPost]
        public IHttpActionResult Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var user = manager.FindByEmail(model.Email);

                    if (user == null)
                        model.Error = "Wrong email or password";

                    user = manager.Find(user.UserName, model.Password);

                    if (user == null)
                        model.Error = "Wrong email or password";

                    model.Name = user.UserName;
                    model.Password = "";
                }
                catch (Exception ex)
                {
                    model.Error = ex.Message;
                }

            }
            else
                model.Error = "Invalid credentials";

            if (string.IsNullOrWhiteSpace(model.Error))
                return Ok(model);
            else
                return InternalServerError(new Exception(model.Error));
        }
    }
}
